﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;
using EffiProz.Core.Results;
using EffiProz.Core.Navigators;

namespace EffiProz.Core
{
    public class StatementSet : StatementDMQL
    {
        Expression expression;
      

        //
        ColumnSchema[] variables;
        int[] variableIndexes;

        //
        public int operationType;
        public const int TRIGGER_SET = 1;
        public const int SELECT_INTO = 2;
        public const int VARIABLE_SET = 3;

        /**
         * Instantiate this as a SET statement.
         */
        public StatementSet(Session session, Table table, RangeVariable[] rangeVars,
                     int[] updateColumnMap, Expression[] colExpressions,
                     ParserDML.CompileContext compileContext)
            : base(StatementTypes.ASSIGNMENT, StatementTypes.X_SQL_DATA_CHANGE,
                session.getCurrentSchemaHsqlName())
        {



            this.operationType = TRIGGER_SET;
            this.targetTable = table;
            this.baseTable = targetTable.getBaseTable();
            this.updateColumnMap = updateColumnMap;
            this.updateExpressions = colExpressions;
            this.updateCheckColumns =
                targetTable.getColumnCheckList(updateColumnMap);
            this.targetRangeVariables = rangeVars;
            _isTransactionStatement = false;

            setDatabseObjects(compileContext);
            checkAccessRights(session);
        }

        public StatementSet(Session session, ParserDML.CompileContext compileContext,
                     ColumnSchema[] variables, Expression e, int[] indexes) :
            base(StatementTypes.ASSIGNMENT, StatementTypes.X_SQL_CONTROL, null)
        {

            this.operationType = VARIABLE_SET;
            _isTransactionStatement = false;
            this.expression = e;
            this.variables = variables;
            variableIndexes = indexes;

            setDatabseObjects(compileContext);
            checkAccessRights(session);
        }

        public StatementSet(Session session, ParserDML.CompileContext compileContext,
                     ColumnSchema[] variables, QueryExpression query, int[] indexes) :
            base(StatementTypes.ASSIGNMENT, StatementTypes.X_SQL_CONTROL, null)
        {

            this.operationType = SELECT_INTO;
            _isTransactionStatement = false;
            this.queryExpression = query;
            this.variables = variables;
            variableIndexes = indexes;

            setDatabseObjects(compileContext);
            checkAccessRights(session);
        }

        public override Result getResult(Session session)
        {

            Result result = null;

            switch (operationType)
            {

                case StatementSet.TRIGGER_SET:
                    result = executeSetStatement(session);
                    break;

                case StatementSet.SELECT_INTO:
                    {
                        Object[] values = queryExpression.getSingleRowValues(session);

                        if (values == null)
                        {
                            result = Result.updateZeroResult;

                            break;
                        }

                        result = executeAssignment(session, values);

                        break;
                    }
                case StatementSet.VARIABLE_SET:
                    {
                        Object[] values = getExpressionValues(session);

                        if (values == null)
                        {
                            result = Result.updateZeroResult;

                            break;
                        }

                        result = executeAssignment(session, values);

                        break;
                    }
                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "StatementSet");
            }

            return result;
        }

        public override void resolve()
        {

            switch (operationType)
            {

                case StatementSet.TRIGGER_SET:
                case StatementSet.SELECT_INTO:
                case StatementSet.VARIABLE_SET:
                    {
                        break;
                    }
                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "StatementSet");
            }
        }

        public override String getSQL()
        {

            StringBuilder sb = new StringBuilder();

            switch (operationType)
            {

                case StatementSet.VARIABLE_SET:
                    {

                        /** @todo - cover row assignment */
                        sb.Append(Tokens.T_SET).Append(' ');
                        sb.Append(variables[0].getName().statementName).Append(' ');
                        sb.Append('=').Append(' ').Append(expression.getSQL());

                        break;
                    }
            }

            return sb.ToString();
        }

        protected String describe(Session session, int blanks)
        {

            StringBuilder sb = new StringBuilder();

            sb.Append('\n');

            for (int i = 0; i < blanks; i++)
            {
                sb.Append(' ');
            }

            sb.Append(Tokens.T_STATEMENT);

            return sb.ToString();
        }

        public override Result execute(Session session)
        {

            Result result;

            try
            {
                materializeSubQueries(session);

                result = getResult(session);
            }
            catch (Exception t)
            {
                result = Result.newErrorResult(t, null);
            }

            if (result.isError())
            {
                result.getException().setStatementType(group, type);
            }

            return result;
        }

        public override String describe(Session session)
        {
            return "";
        }

        public Result executeSetStatement(Session session)
        {

            Table table = targetTable;
            int[] colMap = updateColumnMap;    // column map
            Expression[] colExpressions = updateExpressions;
            SqlType[] colTypes = table.getColumnTypes();
            int index = targetRangeVariables[TriggerDef.NEW_ROW].rangePosition;
            Object[] oldData =
                session.sessionContext.rangeIterators[index].getCurrentRow()
                    .getData();
            Object[] data = StatementDML.getUpdatedData(session, table, colMap,
                colExpressions, colTypes, oldData);

            Array.Copy(data, oldData, data.Length);

            return Result.updateOneResult;
        }

        // this fk references -> other  :  other read lock
        public override void collectTableNamesForRead(OrderedHashSet set)
        {

            for (int i = 0; i < rangeVariables.Length; i++)
            {
                Table rangeTable = rangeVariables[i].rangeTable;
                QNameManager.QName name = rangeTable.getName();

                if (rangeTable.isReadOnly() || rangeTable.isTemp())
                {
                    continue;
                }

                if (name.schema == SqlInvariants.SYSTEM_SCHEMA_QNAME)
                {
                    continue;
                }

                set.add(name);
            }

            for (int i = 0; i < subqueries.Length; i++)
            {
                if (subqueries[i].queryExpression != null)
                {
                    subqueries[i].queryExpression.getBaseTableNames(set);
                }
            }
        }

        public Object[] getExpressionValues(Session session)
        {

            Object[] values;

            if (expression.getType() == OpTypes.ROW)
            {
                values = expression.getRowValue(session);
            }
            else if (expression.getType() == OpTypes.TABLE_SUBQUERY)
            {
                values = expression.subQuery.queryExpression.getSingleRowValues(
                    session);

                if (values == null)
                {

                    // todo - verify semantics
                    return null;
                }
            }
            else
            {
                values = new Object[1];
                values[0] = expression.getValue(session,
                                                variables[0].getDataType());
            }

            return values;
        }

        public Result executeAssignment(Session session, Object[] values)
        {

            for (int j = 0; j < values.Length; j++)
            {
                Object[] data = new object[0];

                switch (variables[j].getType())
                {

                    case SchemaObjectTypes.PARAMETER:
                        data = session.sessionContext.routineArguments;
                        break;

                    case SchemaObjectTypes.VARIABLE:
                        data = session.sessionContext.routineVariables;
                        break;
                }

                int colIndex = variableIndexes[j];

                data[colIndex] =
                    variables[j].getDataType().convertToDefaultType(session,
                        values[j]);
            }

            return Result.updateZeroResult;
        }
    }
}
